package com.example.controller;

import com.example.entity.User;
import com.example.service.RegistrationService;
import com.example.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class RegistrationController {
    @Autowired
    private RegistrationService registrationService;

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        try {
            if (user == null) {
                return Result.error("用户信息不能为空");
            }
            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
                return Result.error("手机号不能为空");
            }
            if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            registrationService.registerUser(user);
            return Result.success("注册成功");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            // 处理数据库唯一约束异常
            if (e.getMessage().contains("users.username")) {
                return Result.error("用户名已被使用");
            } else {
                return Result.error("注册失败: 数据库约束冲突");
            }
        } catch (Exception e) {
            return Result.error("注册失败: " + e.getMessage());
        }
    }
}